package com.ning.weixin.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ning.weixin.entity.AcWechatInfo;
import com.ning.weixin.service.AcApiService;
import com.ning.weixin.utils.wxUtils.WXAuthUtil;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

/**
 * 微信授权Controller
 * @author Cyan
 * @Date:2018/12/13
 */
@Controller
@RequestMapping("/njxs/wechat")
public class WxController {

    private static Logger logger = LoggerFactory.getLogger(WxController.class);
    
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private AcApiService acApiService;

    @GetMapping("/redirectUrl")
    public String test(@RequestParam("openid") String openid) {
        System.out.println("openId="+openid);
        return "redirect:"+"http://www.baidu.com";
    }


    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        logger.info("进入授权方法");
        String url = "https://njxsh5.xiaoxianghuishou.cn/njxs/wechat/userWxGet";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        logger.info("【拿到CODE,跳转获取用户信息页面】获取code,redirectURL={}", redirectURL);
        logger.info("【拿到CODE,跳转获取用户信息页面】获取code,returnUrl={}", returnUrl);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/userWxGet")
    public String userInfo(@RequestParam("code") String code,@RequestParam("state") String returnUrl) throws Exception {
        logger.info("【微信网页授权】code={}", code);
        logger.info("进入用户信息获取方法");
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            logger.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        String access_token = wxMpOAuth2AccessToken.getAccessToken();
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token +
                "&openid="+openId + "&lang=zh_CN";
        JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
        String nickname = userInfo.getString("nickname");
        String headimgurl = userInfo.getString("headimgurl");
        String city = userInfo.getString("city");
        String country = userInfo.getString("country");
        String province = userInfo.getString("province");
        Integer sex = userInfo.getInteger("sex");
        AcWechatInfo t = new AcWechatInfo();
        t.setCity(city);
        t.setCountry(country);
        t.setHeadimgurl(headimgurl);
        t.setNickname(nickname);
        t.setOpenid(openId);
        t.setProvince(province);
        t.setSex(sex);
        acApiService.saveWechatInfo(t);
        logger.info("跳转地址"+"https://njxsh5.xiaoxianghuishou.cn?openid="+ openId);
        return "redirect:" + returnUrl + "?openid="+openId;
    }
    @GetMapping("/getConfig")
    @ResponseBody
    public Map<String,Object> getConfig(@RequestParam("url") String url){
    	Map<String,Object> map = new HashMap<String, Object>();
    	logger.debug("url:"+url);
    	map.put("code", "0");
    	map.put("msg", "success");
    	try {
			map.put("data", wxMpService.createJsapiSignature(url));
		} catch (WxErrorException e) {
			map.put("code", "1");
	    	map.put("msg", e.toString());
		}
    	return map;
    }
    @GetMapping("/getWxUserInfo")
    @ResponseBody
    public Map<String,Object> getWxUserInfo(@RequestParam("code") String code){
    	Map<String,Object> map = new HashMap<String, Object>();
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
    	map.put("code", "0");
    	map.put("msg", "success");
    	try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            String openId = wxMpOAuth2AccessToken.getOpenId();
            String access_token = wxMpOAuth2AccessToken.getAccessToken();
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token +
                    "&openid="+openId + "&lang=zh_CN";
            JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
            String nickname = userInfo.getString("nickname");
            String headimgurl = userInfo.getString("headimgurl");
            String city = userInfo.getString("city");
            String country = userInfo.getString("country");
            String province = userInfo.getString("province");
            Integer sex = userInfo.getInteger("sex");
            AcWechatInfo t = new AcWechatInfo();
            t.setCity(city);
            t.setCountry(country);
            t.setHeadimgurl(headimgurl);
            t.setNickname(nickname);
            t.setOpenid(openId);
            t.setProvince(province);
            t.setSex(sex);
			map.put("data", t);
		} catch (Exception e) {
			map.put("code", "1");
	    	map.put("msg", e.toString());
		}
    	return map;
    }
}
